package com.grwx.omc.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grwx.omc.admin.dao.SysResourceMapper;
import com.grwx.omc.admin.entity.SysResource;
import com.grwx.omc.admin.service.ISysResourceService;
import com.grwx.omc.constant.Constant;
import com.grwx.omc.exception.ValidationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Arrays;

@Service
public class SysResourceServiceImpl extends ServiceImpl<SysResourceMapper, SysResource>
        implements ISysResourceService {

    @Resource
    private SysResourceMapper sysResourceMapper;

    @Override
    public IPage<SysResource> page(Page<SysResource> page, SysResource sysResource) {
        return sysResourceMapper.pageList(page, sysResource);
    }

    @Override
    public void addOrUpdate(SysResource sysResource) {
        if (null == sysResource) {
            throw new ValidationException(Constant.MsgCode.EMPTY_PARAM);
        }
        // 字典类型编码唯一性校验
        uniqueCheck(sysResource);

        if (null == sysResource.getId()) {
            sysResource.preInsert();
            save(sysResource);
        } else {
            sysResource.preUpdate();
            updateById(sysResource);
        }
    }

    /**
     * typeCode唯一校验
     * 规则：同一服务(parentId)下，字典类型不能重复
     * @param sysResource
     */
    private void uniqueCheck(SysResource sysResource) {
//        QueryWrapper<SysResource> wrapper = new QueryWrapper<>();
//        if (null != sysResource.getParentId()) {
//            wrapper.eq("parent_id", sysResource.getParentId());
//        }
//        wrapper.eq("resource_code", sysResource.getResourceCode());
//        wrapper.or().eq("resource_name", sysResource.getResourceName());
//        List<SysResource> existLookupType = list(wrapper);
//        if (!ObjectUtils.isEmpty(existLookupType)) {
//            throw new ValidationException("omc.admin.lookup_type.E001");
//        }
    }


    @Override
    @Transactional
    public void del(Long id) {
        removeById(id);
        remove(new QueryWrapper<SysResource>().eq("parent_id", id));
    }

    @Override
    @Transactional
    public void batchDel(Long[] ids) {
        removeByIds(Arrays.asList(ids));
        remove(new QueryWrapper<SysResource>().in("parent_id", ids));
    }
}
